package com.hys.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hys.dao.good.BrandDao;
import com.hys.pojo.entity.PageBean;
import com.hys.pojo.good.Brand;
import com.hys.pojo.good.BrandQuery;
import com.hys.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandDao brandDao;

    @Override
    public List<Brand> getAllBrand() {
        return brandDao.selectByExample(null);
    }

    @Override
    public PageBean getPageBrand(Integer curPage, Integer pageSize,Brand searchBrand) {
        /*使用分页插件做分页查询*/
        PageHelper.startPage(curPage,pageSize);
        BrandQuery brandQuery = new BrandQuery();
        if (searchBrand != null){ /*添加查询的条件*/
            BrandQuery.Criteria criteria = brandQuery.createCriteria(); /*hibernate*/
            if (searchBrand.getName() != null && !"".equals(searchBrand.getName())){
                criteria.andNameLike("%"+searchBrand.getName()+"%");
            }
            if (searchBrand.getFirstChar() != null && !"".equals(searchBrand.getFirstChar())){
                criteria.andFirstCharLike("%"+searchBrand.getFirstChar()+"%");
            }
        }
        Page<Brand> pageBrand = (Page<Brand> )brandDao.selectByExample(brandQuery);
        return new PageBean(pageBrand.getTotal(),pageBrand.getResult());
    }

    @Override
    public void addBrand(Brand brand) {
        brandDao.insert(brand);
    }

    @Override
    public void updateBrand(Brand brand) {
        brandDao.updateByPrimaryKeySelective(brand);
    }

    @Override
    public void deleteBrand(Long[] ids) {
        if (ids != null) {
            /*for (Long id : ids) {
                brandDao.deleteByPrimaryKey(id);
            }*/
            BrandQuery brandQuery = new BrandQuery();
            BrandQuery.Criteria criteria = brandQuery.createCriteria();
            criteria.andIdIn(Arrays.asList(ids));
            brandDao.deleteByExample(brandQuery);
        }
    }
}
